#include "scoreentry.h"
#include "mainwindow.h"
#include "database.h"
#include <QFormLayout>
#include <QSpacerItem>
#include <QButtonGroup>
#include <QApplication>
#include <QToolTip>

ScoreEntry::ScoreEntry(MainWindow *parent)
    : QWidget(parent), mainWindow(parent), lastHighlightedRoom(""), currentCheckingRoom("")
{
    // 获取数据库实例
    database = mainWindow->getDatabase();

    // 初始化日期为今天
    currentDate = QDate::currentDate();

    setupUi();
    refreshData();
}

ScoreEntry::~ScoreEntry()
{
    // 移除所有事件过滤器
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        if (it.value().roomGroup)
        {
            it.value().roomGroup->removeEventFilter(this);
        }
    }
}

void ScoreEntry::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 顶部控制区域
    QHBoxLayout *controlLayout = new QHBoxLayout();

    // 日期选择
    QLabel *dateLabel = new QLabel("日期:", this);
    dateEdit = new QDateEdit(currentDate, this);
    dateEdit->setCalendarPopup(true);
    dateEdit->setDisplayFormat("yyyy-MM-dd");

    // 单元选择
    QLabel *unitLabel = new QLabel("单元:", this);
    unitSelect = new QComboBox(this);

    // 保存按钮
    saveButton = new QPushButton("保存数据", this);
    saveButton->setStyleSheet("background-color: #28a745; color: white; padding: 5px 15px;");

    controlLayout->addWidget(dateLabel);
    controlLayout->addWidget(dateEdit);
    controlLayout->addSpacing(20);
    controlLayout->addWidget(unitLabel);
    controlLayout->addWidget(unitSelect);
    controlLayout->addStretch();
    controlLayout->addWidget(saveButton);

    mainLayout->addLayout(controlLayout);

    // 滚动区域，用于容纳所有房间的评分控件
    scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setFrameShape(QFrame::NoFrame);

    scrollContent = new QWidget(scrollArea);
    roomsLayout = new QVBoxLayout(scrollContent);

    scrollArea->setWidget(scrollContent);
    mainLayout->addWidget(scrollArea);

    // 连接信号和槽
    connect(dateEdit, &QDateEdit::dateChanged, this, &ScoreEntry::onDateChanged);
    connect(unitSelect, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
            this, &ScoreEntry::onUnitChanged);
    connect(saveButton, &QPushButton::clicked, this, &ScoreEntry::saveScores);
}

void ScoreEntry::refreshData()
{
    // 清空单元选择
    unitSelect->clear();

    // 加载单元列表
    QStringList units = database->getBuildingUnits();
    unitSelect->addItems(units);

    // 如果有单元，默认选择第一个并加载其房间
    if (!units.isEmpty())
    {
        currentUnit = units.first();
        loadRooms();
    }
}

void ScoreEntry::loadRooms()
{
    // 清除旧的房间控件
    QLayoutItem *item;
    while ((item = roomsLayout->takeAt(0)) != nullptr)
    {
        if (QWidget *widget = item->widget())
        {
            widget->deleteLater();
        }
        delete item;
    }

    roomControls.clear();

    // 获取当前单元的房间列表
    QStringList rooms = database->getRoomsByUnit(currentUnit);

    if (rooms.isEmpty())
    {
        QLabel *noRoomsLabel = new QLabel("该单元下没有房间", scrollContent);
        roomsLayout->addWidget(noRoomsLabel);
        return;
    }

    // 创建房间列表标题
    QLabel *titleLabel = new QLabel(currentUnit + " 房间评分:", scrollContent);
    QFont titleFont = titleLabel->font();
    titleFont.setBold(true);
    titleFont.setPointSize(12);
    titleLabel->setFont(titleFont);
    roomsLayout->addWidget(titleLabel);

    // 创建每个房间的评分控件
    for (const QString &room : rooms)
    {
        QGroupBox *roomGroup = new QGroupBox("", scrollContent);
        // 设置初始样式，与高亮/非高亮样式保持相同的尺寸
        roomGroup->setStyleSheet("QGroupBox { background-color: transparent; border: 1px solid transparent; border-radius: 5px; }");
        QHBoxLayout *roomLayout = new QHBoxLayout(roomGroup);

        // 房间标签
        QLabel *roomLabel = new QLabel(room, roomGroup);
        roomLabel->setMinimumWidth(100);

        // 评分单选按钮
        QRadioButton *excellentRadio = new QRadioButton("优", roomGroup);
        QRadioButton *goodRadio = new QRadioButton("良", roomGroup);
        QRadioButton *poorRadio = new QRadioButton("差", roomGroup);

        // 默认选择"良"
        goodRadio->setChecked(true);

        // 按钮组，确保单选
        QButtonGroup *scoreGroup = new QButtonGroup(roomGroup);
        scoreGroup->addButton(excellentRadio);
        scoreGroup->addButton(goodRadio);
        scoreGroup->addButton(poorRadio);

        // 问题复选框，只在选择"差"时启用
        QCheckBox *fireCheck = new QCheckBox("消防", roomGroup);
        QCheckBox *smokingCheck = new QCheckBox("抽烟", roomGroup);
        QCheckBox *sanitaryCheck = new QCheckBox("卫生", roomGroup);
        QCheckBox *safetyCheck = new QCheckBox("安全", roomGroup);

        fireCheck->setEnabled(false);
        smokingCheck->setEnabled(false);
        sanitaryCheck->setEnabled(false);
        safetyCheck->setEnabled(false);

        // 当选择"差"时启用问题复选框
        connect(poorRadio, &QRadioButton::toggled, fireCheck, &QCheckBox::setEnabled);
        connect(poorRadio, &QRadioButton::toggled, smokingCheck, &QCheckBox::setEnabled);
        connect(poorRadio, &QRadioButton::toggled, sanitaryCheck, &QCheckBox::setEnabled);
        connect(poorRadio, &QRadioButton::toggled, safetyCheck, &QCheckBox::setEnabled);

        // 连接"差"选择的改变信号到验证函数
        connect(poorRadio, &QRadioButton::toggled, this, &ScoreEntry::onPoorScoreToggled);

        // 连接问题类型复选框的状态改变信号到验证函数
        connect(fireCheck, &QCheckBox::stateChanged, this, &ScoreEntry::validatePoorScoreIssues);
        connect(smokingCheck, &QCheckBox::stateChanged, this, &ScoreEntry::validatePoorScoreIssues);
        connect(sanitaryCheck, &QCheckBox::stateChanged, this, &ScoreEntry::validatePoorScoreIssues);
        connect(safetyCheck, &QCheckBox::stateChanged, this, &ScoreEntry::validatePoorScoreIssues);

        // 添加到布局
        roomLayout->addWidget(roomLabel);
        roomLayout->addWidget(excellentRadio);
        roomLayout->addWidget(goodRadio);
        roomLayout->addWidget(poorRadio);
        roomLayout->addSpacing(20);
        roomLayout->addWidget(fireCheck);
        roomLayout->addWidget(smokingCheck);
        roomLayout->addWidget(sanitaryCheck);
        roomLayout->addWidget(safetyCheck);
        roomLayout->addStretch();

        roomsLayout->addWidget(roomGroup);

        // 保存控件引用
        RoomScoreControls controls;
        controls.roomGroup = roomGroup; // 保存房间组引用
        controls.roomLabel = roomLabel;
        controls.excellentRadio = excellentRadio;
        controls.goodRadio = goodRadio;
        controls.poorRadio = poorRadio;
        controls.fireCheck = fireCheck;
        controls.smokingCheck = smokingCheck;
        controls.sanitaryCheck = sanitaryCheck;
        controls.safetyCheck = safetyCheck;

        roomControls[room] = controls;

        // 为房间组添加事件过滤器，捕获鼠标进入和离开事件
        roomGroup->setObjectName("roomGroup_" + room); // 设置对象名，便于在事件过滤器中识别
        roomGroup->installEventFilter(this);
    }

    // 添加底部空间
    roomsLayout->addStretch();

    // 加载已有的评分数据
    loadScoreData();
}

void ScoreEntry::loadScoreData()
{
    // 获取当前日期和单元的评分记录
    QList<Database::ScoreRecord> records = database->getScoresByDateAndUnit(
        currentDate.toString("yyyy-MM-dd"), currentUnit);

    // 先恢复默认状态：所有房间勾选"良"
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        it.value().excellentRadio->setChecked(false);
        it.value().goodRadio->setChecked(true);
        it.value().poorRadio->setChecked(false);

        it.value().fireCheck->setChecked(false);
        it.value().smokingCheck->setChecked(false);
        it.value().sanitaryCheck->setChecked(false);
        it.value().safetyCheck->setChecked(false);
    }

    // 应用已有的评分记录
    for (const Database::ScoreRecord &record : records)
    {
        if (roomControls.contains(record.room))
        {
            RoomScoreControls &controls = roomControls[record.room];

            if (record.score == "优")
            {
                controls.excellentRadio->setChecked(true);
            }
            else if (record.score == "良")
            {
                controls.goodRadio->setChecked(true);
            }
            else if (record.score == "差")
            {
                controls.poorRadio->setChecked(true);

                // 检查问题
                QStringList issues = record.issues.split(",", QString::SkipEmptyParts);
                controls.fireCheck->setChecked(issues.contains("消防"));
                controls.smokingCheck->setChecked(issues.contains("抽烟"));
                controls.sanitaryCheck->setChecked(issues.contains("卫生"));
                controls.safetyCheck->setChecked(issues.contains("安全"));
            }
        }
    }
}

void ScoreEntry::onUnitChanged(const QString &unit)
{
    currentUnit = unit;
    loadRooms();
}

void ScoreEntry::onDateChanged(const QDate &date)
{
    currentDate = date;
    loadScoreData();
}

void ScoreEntry::saveScores()
{
    // 判断是否需要覆盖已有数据
    bool hasExistingData = false;
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        QString room = it.key();
        if (database->hasScoreRecordForDate(currentDate.toString("yyyy-MM-dd"), currentUnit, room))
        {
            hasExistingData = true;
            break;
        }
    }

    // 如果有已存在的数据，询问是否覆盖
    if (hasExistingData && !confirmOverwrite())
    {
        return;
    }

    // 验证所有选择"差"的房间是否都选择了至少一种问题类型
    QString invalidRooms;
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        QString room = it.key();
        RoomScoreControls &controls = it.value();

        if (controls.poorRadio->isChecked())
        {
            // 检查是否有勾选问题类型
            if (!controls.fireCheck->isChecked() &&
                !controls.smokingCheck->isChecked() &&
                !controls.sanitaryCheck->isChecked() &&
                !controls.safetyCheck->isChecked())
            {
                if (!invalidRooms.isEmpty())
                    invalidRooms += ", ";
                invalidRooms += room;
            }
        }
    }

    // 如果有选择"差"但未选择问题类型的房间，显示错误并终止保存
    if (!invalidRooms.isEmpty())
    {
        QMessageBox::warning(this, "无效的评分数据",
                             QString("以下房间选择了\"差\"评分，但未勾选任何问题类型：\n%1\n\n请选择至少一种问题类型").arg(invalidRooms));
        return;
    }

    // 开始保存数据
    int successCount = 0;
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        QString room = it.key();
        RoomScoreControls &controls = it.value();

        QString score;
        QString issues;

        if (controls.excellentRadio->isChecked())
        {
            score = "优";
        }
        else if (controls.goodRadio->isChecked())
        {
            score = "良";
        }
        else if (controls.poorRadio->isChecked())
        {
            score = "差";

            // 收集问题
            QStringList issueList;
            if (controls.fireCheck->isChecked())
                issueList.append("消防");
            if (controls.smokingCheck->isChecked())
                issueList.append("抽烟");
            if (controls.sanitaryCheck->isChecked())
                issueList.append("卫生");
            if (controls.safetyCheck->isChecked())
                issueList.append("安全");

            issues = issueList.join(",");
        }

        // 保存到数据库
        if (database->saveScoreRecord(currentDate.toString("yyyy-MM-dd"), currentUnit, room, score, issues))
        {
            successCount++;
        }
    }

    QMessageBox::information(this, "保存成功",
                             QString("成功保存 %1 个房间的评分信息").arg(successCount));
}

bool ScoreEntry::confirmOverwrite()
{
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认覆盖",
                                                              "当前日期已有评分数据，是否覆盖？",
                                                              QMessageBox::Yes | QMessageBox::No);

    return (reply == QMessageBox::Yes);
}

// 事件过滤器实现
bool ScoreEntry::eventFilter(QObject *watched, QEvent *event)
{
    // 检查事件是否来自房间组
    if (watched->objectName().startsWith("roomGroup_"))
    {
        QString room = watched->objectName().mid(10); // 移除"roomGroup_"前缀，获取房间号

        if (event->type() == QEvent::Enter)
        {
            // 鼠标进入事件
            if (roomControls.contains(room))
            {
                // 保存当前高亮的房间
                lastHighlightedRoom = room;

                // 设置高亮背景色 - 使用不改变元素尺寸的样式
                roomControls[room].roomGroup->setStyleSheet("QGroupBox { background-color: #e6f2ff; border: 1px solid transparent; border-radius: 5px; }");
            }
            return true; // 事件已处理
        }
        else if (event->type() == QEvent::Leave)
        {
            // 鼠标离开事件
            if (roomControls.contains(room))
            {
                // 恢复正常背景色 - 保持相同的边框宽度，但使用透明色
                roomControls[room].roomGroup->setStyleSheet("QGroupBox { background-color: transparent; border: 1px solid transparent; border-radius: 5px; }");

                // 清除高亮记录
                if (lastHighlightedRoom == room)
                {
                    lastHighlightedRoom = "";
                }
            }
            return true; // 事件已处理
        }
    }

    // 对于其他事件，交给父类处理
    return QWidget::eventFilter(watched, event);
}

void ScoreEntry::onRoomGroupEntered()
{
    // 获取发送信号的对象
    QGroupBox *sender = qobject_cast<QGroupBox *>(QObject::sender());
    if (!sender)
        return;

    // 从对象名中提取房间号
    QString room = sender->objectName().mid(10); // 移除"roomGroup_"前缀

    if (roomControls.contains(room))
    {
        // 设置高亮背景色 - 使用不改变元素尺寸的样式
        roomControls[room].roomGroup->setStyleSheet("QGroupBox { background-color: #e6f2ff; border: 1px solid transparent; border-radius: 5px; }");
        lastHighlightedRoom = room;
    }
}

void ScoreEntry::onRoomGroupLeft()
{
    // 获取发送信号的对象
    QGroupBox *sender = qobject_cast<QGroupBox *>(QObject::sender());
    if (!sender)
        return;

    // 从对象名中提取房间号
    QString room = sender->objectName().mid(10); // 移除"roomGroup_"前缀

    if (roomControls.contains(room))
    {
        // 恢复正常背景色 - 保持相同的边框宽度，但使用透明色
        roomControls[room].roomGroup->setStyleSheet("QGroupBox { background-color: transparent; border: 1px solid transparent; border-radius: 5px; }");

        if (lastHighlightedRoom == room)
        {
            lastHighlightedRoom = "";
        }
    }
}

// 实现新的槽函数
void ScoreEntry::onPoorScoreToggled(bool checked)
{
    if (!checked)
        return;

    // 获取发送信号的"差"单选按钮
    QRadioButton *sender = qobject_cast<QRadioButton *>(QObject::sender());
    if (!sender)
        return;

    // 遍历找到对应的房间
    for (auto it = roomControls.begin(); it != roomControls.end(); ++it)
    {
        if (it.value().poorRadio == sender)
        {
            currentCheckingRoom = it.key();
            validatePoorScoreIssues();
            break;
        }
    }
}

void ScoreEntry::validatePoorScoreIssues()
{
    // 确保有当前检查的房间
    if (currentCheckingRoom.isEmpty())
        return;

    // 获取该房间的控件
    if (!roomControls.contains(currentCheckingRoom))
        return;

    RoomScoreControls &controls = roomControls[currentCheckingRoom];

    // 如果选择了"差"但没有勾选任何问题类型
    if (controls.poorRadio->isChecked() &&
        !controls.fireCheck->isChecked() &&
        !controls.smokingCheck->isChecked() &&
        !controls.sanitaryCheck->isChecked() &&
        !controls.safetyCheck->isChecked())
    {

        // 高亮提示问题区域
        controls.fireCheck->setStyleSheet("QCheckBox { color: red; font-weight: bold; }");
        controls.smokingCheck->setStyleSheet("QCheckBox { color: red; font-weight: bold; }");
        controls.sanitaryCheck->setStyleSheet("QCheckBox { color: red; font-weight: bold; }");
        controls.safetyCheck->setStyleSheet("QCheckBox { color: red; font-weight: bold; }");

        // 可选：显示提示文本
        QToolTip::showText(QCursor::pos(), "请至少选择一种问题类型", this);
    }
    else
    {
        // 恢复正常样式
        controls.fireCheck->setStyleSheet("");
        controls.smokingCheck->setStyleSheet("");
        controls.sanitaryCheck->setStyleSheet("");
        controls.safetyCheck->setStyleSheet("");
    }
}